package com.dayaokeji.rhythmschoolstudent.client.mine.account;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.main.MainActivity;
import com.dayaokeji.rhythmschoolstudent.databases.dao.UserInfoDao;
import com.dayaokeji.rhythmschoolstudent.event.UpdateCourseEvent;
import com.dayaokeji.rhythmschoolstudent.utils.InputUtils;
import com.dayaokeji.rhythmschoolstudent.utils.JPushAliasUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.SmsApi;
import com.dayaokeji.server_api.api.UserApi;
import com.dayaokeji.server_api.domain.SendSmsType;
import com.dayaokeji.server_api.domain.Sms;
import com.dayaokeji.server_api.domain.UserInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 学号工号登录，绑定手机号码
 */
public class BindMobileActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_mobile)
    EditText etMobile;
    @BindView(R.id.et_verify_code)
    EditText etVerifyCode;
    @BindView(R.id.btn_send_verify_code)
    Button btnSendVerifyCode;

    private String mobile;
    private static final UserApi userApi = ApiUtils.getApi(UserApi.class);
    private Call<ServerResponse<UserInfo>> bindPhoneCall;
    private final SmsApi smsApi = ApiUtils.getApi(SmsApi.class);
    private Call<ServerResponse<Void>> sendSmsCall;
    private Call<ServerResponse<Boolean>> validateSmsCall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_mobile);
        setSupportActionBar(toolbar);
    }

    @OnClick({
            R.id.btn_send_verify_code,
            R.id.btn_bind_mobile
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_send_verify_code:
                sendVerifyCode();
                break;
            case R.id.btn_bind_mobile:
                checkVerifyCode();
                break;
        }
    }


    /**
     * 发送验证码
     */
    private void sendVerifyCode() {
        if (InputUtils.validateInput(etMobile,"请输入手机号码")) {
            mobile = etMobile.getText().toString().replace(" ", "").trim();
            if (mobile.length() == 11 && TextUtils.isDigitsOnly(mobile)) {
                final Sms sendSms = new Sms();
                sendSms.setPhone(mobile);
                sendSms.setType(SendSmsType.BINDING.getType());
                sendSmsCall = smsApi.send(sendSms);
                sendSmsCall.enqueue(new ServerCallback<Void>(this,"正在发送短信验证码...") {
                    @Override
                    public void onResponse(boolean success, ServerResponse<Void> response) {
                        if (success) {
                            if (countDownTimer != null) {
                                countDownTimer.start();
                            }
                            ToastUtils.success("发送验证码成功");
                        }else{
                            ToastUtils.warning("发送验证码失败");
                            if (countDownTimer != null) {
                                countDownTimer.onFinish();
                            }
                        }
                    }
                });
            }else{
                ToastUtils.warning("请输入11位手机号码");
            }

        }
    }

    /**
     * 验证验证码
     */
    private void checkVerifyCode() {
        if (InputUtils.validateInput(etMobile,"请输入手机号码") && InputUtils.validateInput(etVerifyCode,"请输入验证码")) {
            String verifyCode = etVerifyCode.getText().toString().trim();
            final Sms sms = new Sms();
            sms.setPhone(mobile);
            sms.setType(SendSmsType.BINDING.getType());
            sms.setCode(verifyCode);
            validateSmsCall = smsApi.validate(sms);
            validateSmsCall.enqueue(new ServerCallback<Boolean>(this,"正在验证...") {
                @Override
                public void onResponse(boolean success, ServerResponse<Boolean> response) {
                    if (success) {
                        if (response.getBody() != null && response.getBody().booleanValue()) {
                            bindPhone();
                        }else{
                            ToastUtils.warning("验证码失效");
                            if (countDownTimer != null) {
                                countDownTimer.onFinish();
                            }
                        }
                    }
                }
            });
        }
    }

    /**
     * 绑定手机号码
     */
    private void bindPhone() {
        final UserInfo userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            Map<String,String> params = new HashMap<>();
            params.put("workNo", userInfo.getWorkNo());
            params.put("phone",mobile);
            params.put("platform","1");
            bindPhoneCall = userApi.bindPhone(params);
            bindPhoneCall.enqueue(new ServerCallback<UserInfo>(this,"正在绑定...") {
                @Override
                public void onResponse(boolean success, ServerResponse<UserInfo> response) {
                    if (success) {
                        UserInfo userInfo = response.getBody();
                        initUserInfo(userInfo);
                    }
                }

                @Override
                public void onFailure(Call<ServerResponse<UserInfo>> call, Throwable t) {
                    super.onFailure(call, t);
                    if (!isFinishing()) {
                        startActivity(new Intent(BindMobileActivity.this, StudentIdLoginActivity.class));
                        ActivityStackManager.finish();
                    }
                }
            });
        }else{
            ToastUtils.warning("当前账户信息不完整，请重新登录");
        }
    }


    /**
     * 初始化用户信息，存储用户信息
     * @param userInfo
     */
    private void initUserInfo(UserInfo userInfo) {
        if (!UserUtils.checkIsStudent(this,userInfo)) {
            return;
        }
        UserUtils.setUserInfo(userInfo);
        UserUtils.setAccessToken(userInfo.getToken());
        UserInfoDao.saveUserInfo(userInfo);
        JPushAliasUtils.getInstance().setJPushAlias(this);
        EventBus.getDefault().post(new UpdateCourseEvent());
        startActivity(new Intent(BindMobileActivity.this, MainActivity.class));
        ActivityStackManager.finish();
    }

    private CountDownTimer countDownTimer = new CountDownTimer(60 * 1000,1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (btnSendVerifyCode != null) {
                btnSendVerifyCode.setEnabled(false);
                btnSendVerifyCode.setText("已发送（ " + millisUntilFinished / 1000 + " s）");
            }
        }

        @Override
        public void onFinish() {
            if (btnSendVerifyCode != null) {
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                }
                btnSendVerifyCode.setText("重新获取验证码");
                btnSendVerifyCode.setEnabled(true);
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bindPhoneCall != null) {
            bindPhoneCall.cancel();
        }
        if (validateSmsCall != null) {
            validateSmsCall.cancel();
        }
        if (sendSmsCall != null) {
            sendSmsCall.cancel();
        }
    }
}
